// pages/history/history.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    host: "",
    loadingState: 0,
    pageNum: 1,
    items: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({host: app.globalData.host})
    this.getHistoryItems()
  },

  
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
    if(this.data.loadingState != 2){
      this.setData({loadingState: 1})
      this.getHistoryItems();
    }
    
  },

  getHistoryItems: function(){
    let token = wx.getStorageSync('token')
    let pageNum = this.data.pageNum
    let host = app.globalData.host
    wx.request({
      url: host + '/item/history',
      header: {
        'authorization': token,
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        pageNum: pageNum
      },
      success: (res) => {
        let itemList = res.data.data.records;
        let newItems = this.data.items.concat(itemList)
        if (itemList.length < 30) {
          this.setData({
            items: newItems,
            loadingState: 2,
            pageNum: pageNum + 1
          })
        } else {
          this.setData({
            items: newItems,
            loadingState: 0,
            pageNum: pageNum + 1
          })
        }

      },
      fail: (e) => {
        console.log(e)
      }
    })
  },

  deleteItem: function(e){
    console.log(e)
    let itemId = e.currentTarget.dataset.id
    let index = e.currentTarget.dataset.index
    let token = wx.getStorageSync('token')
    let host = app.globalData.host
    wx.request({
      url: host + '/item/delete',
      method: 'POST',
      header: {
        'authorization': token,
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        id: itemId
      },
      success: (res) => {
        if(res.data.data == 1){
          this.data.items[index].state = 1
          this.setData({
            items : this.data.items
          })
          wx.showToast({title: '删除成功'})
        }else{
          wx.showToast({ title: '删除失败' })
        }
      },
      fail: (e) => {
        console.log(e)
      }
    })
  }
})